package com.note.user.service.impl;

import cn.hutool.core.date.DateUtil;
import com.note.user.constants.ResponseCodeConstants;
import com.note.user.dao.UserLoginRepository;
import com.note.user.domain.User;
import com.note.user.dto.UserDto;
import com.note.user.service.TokenService;
import com.note.user.service.UserLoginService;
import com.note.user.util.JwtUtil;
import com.note.user.util.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

/**
 * @Package：com.note.user.service.impl
 * @Name：LoginServiceImpl
 * @Author：热伊木
 * @Email：uyevan@163.com
 * @Date：2023-12-11-11:22
 * @Description：登录服务实现
 */
@Service
public class UserLoginServiceImpl implements UserLoginService {

    @Autowired
    private UserLoginRepository userLoginRepository;
    @Autowired
    private TokenService tokenService;

    /*用户登录验证*/
    @Override
    public int validateUser(UserDto userDto) {
        User user = userLoginRepository.selectUser(userDto);
        //用户不存在
        if (user == null) {
            return ResponseCodeConstants.USER_NOT_FOUND;
        }
        //密码错误
        if (!userDto.getPassword().equals(user.getPassword())) {
            return ResponseCodeConstants.WRONG_PASSWORD;
        }
        //封禁用户
        if (user.getStatus() == 0) {
            /*移除令牌*/
            RedisUtils.removeValue(userDto.getUsername());
            return ResponseCodeConstants.USER_BANNED;
        }
        String userToken = tokenService.getToken(userDto);
        //未登录
        if (!StringUtils.hasLength(userToken)) {
            initToken(userDto);
        }
        //已过期
        else if (JwtUtil.getExpiresAt(userToken) - DateUtil.current() > 0L) {
            //令牌更新 [过期时间 - 现在时间 > 0]
            refreshToken(userDto);
        }
        /*Redis中不存在则写入*/
        else if (!RedisUtils.exists(userDto.getUsername())) {
            /*更新Redis中的值*/
            loadToken(userDto);
        }
        return ResponseCodeConstants.LOGIN_SUCCESS;
    }

    /*获取用户信息*/
    @Override
    public User getUserInfo(UserDto userDto) {
        return userLoginRepository.selectUser(userDto);
    }

    /*用户是否存在*/
    @Override
    public boolean isUserExist(UserDto userDto) {
        User user = userLoginRepository.selectUser(userDto);
        //用户不存在
        return user != null;
    }

    /**
     * 初始化用户令牌
     *
     * @param userDto
     */
    private void initToken(UserDto userDto) {
        loadToken(userDto);
    }

    /**
     * 登录刷新令牌
     *
     * @param userDto
     */
    private void refreshToken(UserDto userDto) {
        loadToken(userDto);
    }

    /**
     * 初始化或更新Token
     *
     * @param userDto userDto
     */
    private void loadToken(UserDto userDto) {
        //（已过期）设置新的令牌
        String newToken = tokenService.generateToken(userDto);
        tokenService.setToken(userDto, newToken);
        /*更新Redis中的值*/
        RedisUtils.saveValue(userDto.getUsername(), newToken, 7, TimeUnit.DAYS);
    }
}
